import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/match/req_match.dart';
import 'package:flutter_changdian_football/base/base_page_controller.dart';
import 'package:flutter_changdian_football/config/enum/refresh.dart';
import 'package:flutter_changdian_football/model/match/game_record_model.dart';
import 'package:flutter_changdian_football/utils/ext/refresher_extension.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

class GameRecordController extends BaseGetPageController {

  List<GameRecordModel> gameRecordModelList = [];

  GameRecordController({
    this.clubId
  });

  final String? clubId;

  @override
  void requestData(
    RefreshController controller, 
    {
      Refresh refresh = Refresh.first
    }
  ) async {
    var response;

    if (clubId == null) {
      response = await ReqMatch.userMatchRecords(
        pageNum: page
      );
    } else {
      response = await ReqMatch.clubMatchList(
        pageNum: page,
        clubId: clubId
      );
    }

    if (response.status == Status.completed) {
      if (response.data['code'] == '200') {
        /// 判断是否为最后一页, 如果是， over传true， 否则false
        if (response.data['data']['hasNextPage'] == false) {
          RefreshExtension.onSuccess(controller, refresh, true); 
        } else {
          RefreshExtension.onSuccess(controller, refresh, false);
        }

        /// 下拉刷新需要清除列表
        if (refresh != Refresh.down) {
          gameRecordModelList.clear();
          update();
        }

        for (int i = 0; i < response.data['data']['userMatchRecordVOList'].length; i++) {
          gameRecordModelList.add(GameRecordModel.fromJson(response.data['data']['userMatchRecordVOList'][i]));
        }

        showSuccess(gameRecordModelList);
        update();
      } else if (response.data['code'] == 401) {
        RefreshExtension.onError(controller, refresh);
      } else {
        showError();  
        RefreshExtension.onError(controller, refresh);
      }
    } else {
      showError();  
      RefreshExtension.onError(controller, refresh);
    }
  }

}